<template>
    <div class="debris-user-list" v-loading="loading">
        <div class="input-box">
            <span class="input-title" style="margin-left:0px;">关联游戏</span>
            <el-select
                style="width:200px"
                v-model="listParams.gameName"
                clearable
                filterable
                :filter-method="filterMethod"
                :loading="gameLoading"
                @change="selectChange"
                placeholder="请输入并选择游戏">
                <el-option
                    v-for="item in gameList"
                    :key="item.gameid"
                    :label="item.appName"
                    :value="item.appName">
                        <span style="float: left">
                            <span>{{ item.appName }}</span>
                            <span v-if="item.status === -1" style="color:red;font-size:12px;margin:0 5px;">下架</span>
                        </span>
                        <span style="float: right; color: #8492a6; font-size: 13px">{{ item.gameid }}</span>
                </el-option>
            </el-select>
            <span class="input-title">商品名称</span>
            <el-input
                placeholder="请输入商品名称"
                @keyup.enter.native="getList(1)"
                style="width:160px;"
                clearable
                v-model.trim="listParams.pieceName">
                <i slot="prefix" class="el-input__icon el-icon-search"></i>
            </el-input>
            <span class="input-title">用户ID</span>
            <el-input
                placeholder="请输入用户ID"
                @keyup.enter.native="getList(1)"
                style="width:150px;"
                clearable
                v-model.trim="listParams.userId">
                <i slot="prefix" class="el-input__icon el-icon-search"></i>
            </el-input>
            <span class="input-title">兑换状态</span>
            <el-select
                @change="selectChange"
                style="width:100px;"
                v-model="listParams.rewardStatus">
                <el-option label="全部" :value="null"></el-option>
                <el-option label="未兑换" :value="0"></el-option>
                <el-option label="已兑换" :value="1"></el-option>
            </el-select>
        </div>
        <div class="input-box">
            <span class="input-title" style="margin-left:0px;margin-right:22px">兑换码</span>
            <el-input
                placeholder="请输入兑换码"
                @keyup.enter.native="getList(1)"
                style="width:200px;"
                clearable
                v-model.trim="listParams.cdKey">
            </el-input>
            <span class="input-title">确认兑换时间</span>
                <el-date-picker
                    @change="getList(1, 10)"
                    v-model="exchangeDate"
                    :clearable="true"
                    type="daterange"
                    value-format="yyyy-MM-dd"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期">
                </el-date-picker>
            <el-button type="primary" class="btn" @click="getList(1)">查询</el-button>
            <el-button type="success" class="btn" @click="exportExcel">导出</el-button>
        </div>

        <div class="table-box">
            <el-table :data="tableData" ref="table" @sort-change="sortChange" border style="width: 100%">
                <el-table-column fixed width="80" prop="userId" label="用户ID"></el-table-column>
                <el-table-column min-width="100" label="用户昵称" prop="userName"></el-table-column>
                <el-table-column min-width="100" prop="name" label="商品名称"></el-table-column>
                <el-table-column min-width="100" label="商品图鉴">
                    <template slot-scope="scope">
                        <div class="cover">
                            <img :src="scope.row.thumbnail" alt="">
                        </div>
                    </template>
                </el-table-column>
                <el-table-column min-width="80" label="商品类型">
                    <template>
                        <div>皮肤</div>
                    </template>
                </el-table-column>
                <el-table-column min-width="150" label="关联游戏">
                    <template slot-scope="scope">
                        <div class="table-btn" @click="toGame(scope.row.gameId)">{{ scope.row.gameName || '-' }}</div>
                    </template>
                </el-table-column>
                <el-table-column min-width="180" label="兑换码" prop="key"></el-table-column>
                <el-table-column min-width="80" label="碎片数" prop="piecePrice"></el-table-column>
                <el-table-column min-width="180" prop="auditstatus" label="兑换时间">
                    <template slot-scope="scope">
                        <div>{{ scope.row.exchangeTime }}</div>
                    </template>
                </el-table-column>
                <el-table-column min-width="180" prop="auditstatus" label="确认兑换时间">
                    <template slot-scope="scope">
                        <div v-if="scope.row.confirmTime">{{ tableFormatDate(scope.row.confirmTime) }}</div>
                        <div v-else>-</div>
                    </template>
                </el-table-column>
                <el-table-column min-width="100" label="发放形式">
                    <template slot-scope="scope">
                        <div v-if="scope.row.exchangeType === 1">微信转账</div>
                        <div v-if="scope.row.exchangeType === 2">游戏赠送</div>
                        <div v-if="scope.row.exchangeType === 3">金币赠送</div>
                        <div v-if="!scope.row.exchangeType">-</div>
                    </template>
                </el-table-column>
                <el-table-column fixed="right" label="操作">
                    <template slot-scope="scope">
                        <div>
                            <el-button v-if="scope.row.rewardStatus === 0" @click="changeStatus(scope.row)" type="text" size="small" style="color:#67C23A;">确认</el-button>
                            <span v-else>已兑换</span>
                        </div>
                    </template>
                </el-table-column>
            </el-table>
        </div>

        <div class="tools">
            <p>已兑换碎片数: {{ this.exchangePieceCount }}</p>
            <el-pagination
                @size-change="sizeChange"
                @current-change="pageChange"
                :current-page="pageNum"
                :page-sizes="_pageSizes"
                :page-size="pageSize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total">
            </el-pagination>
        </div>
        <el-dialog :title="dialogTit" :visible.sync="dialogVisible" width="35%" :before-close="handleClose">
            <div class="dialog-slot">
                <div class="dialog-item">
                    <span style="margin-right: 10px">发放形式：</span>
                    <el-select v-model="exchangeParams.exchangeType" placeholder="请选择发放形式">
                        <el-option label="微信转账" :value="1"></el-option>
                        <el-option label="游戏赠送" :value="2"></el-option>
                        <el-option label="金币赠送" :value="3"></el-option>
                    </el-select>
                </div>
                <div>
                    <span style="margin-right: 10px">发放数量：</span>
                    <el-input
                        placeholder="请输入发放数量"
                        @keyup.enter.native="getList(1)"
                        style="width:200px;"
                        clearable
                        v-model.trim="exchangeParams.number">
                    </el-input>
                </div>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="dialogSure">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import { formatDate } from '@/utils/utils'
export default {
    data () {
        return {
            dialogTit: '',
            tableData: [],
            exchangeDate: [],
            exchangeParams: {},
            listParams: {
                gameName: '',
                pieceName: '',
                userId: ''
            },
            exchangePieceCount: 0,
            pageNum: 1,
            pageSize: this._pageSize,
            total: 0,
            loading: false,
            dialogVisible: false,
            gameLoading: false, // 查询游戏的loading
            gameList: [] // 游戏列表
        }
    },
    created () {
        this.listParams.gameName = this.$route.query.gameName || ''
        this.listParams.pieceName = this.$route.query.name || ''
        this.getList(this.pageNum)
    },
    methods: {
        // 获取列表
        async getList (pageNum) {
            if (this.loading) return
            this.pageNum = pageNum
            this.loading = true
            let params = {
                pageNum,
                pageSize: this.pageSize,
                fromDate: '',
                endDate: ''
            }
            if (this.exchangeDate && this.exchangeDate.length) {
                params.fromDate = this.exchangeDate[0] + ' 00:00:00'
                params.endDate = this.exchangeDate[1] + ' 23:59:59'
            }
            params = Object.assign(params, this.listParams)
            let res = await this.$http.get('/lottrey/selectPieceExchange', {
                params
            })
            if (res.code === '0') {
                this.exchangePieceCount = res.data.exchangePieceCount
                res.data.pieceExchangeVoList.map(item => {
                    item.exchangeTime = formatDate(item.exchangeTime, 'YYYY-MM-DD HH:MM:SS')
                })
                this.tableData = res.data.pieceExchangeVoList
                this.total = res.count
            } else {
                this.$message({
                    type: 'error',
                    message: '系统异常，请稍后再试'
                })
            }
            this.loading = false
        },
        exportExcel () {
            this.$confirm(`是否导出全部兑换明细?`, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                let params = {
                    pageNum: 1,
                    pageSize: 999
                }
                params = Object.assign(params, this.listParams)
                this.$http.post('/lottrey/exportPieceExchange', params, {
                    responseType: 'arraybuffer'
                }).then(res => {
                    const aLink = document.createElement('a')
                    let blob = new Blob([res], { type: 'application/vnd.ms-excel' })
                    aLink.href = URL.createObjectURL(blob)
                    aLink.setAttribute('download', '兑换明细' + '.xlsx') // 设置下载文件名称
                    aLink.click()
                })
            })
        },
        // 后端排序
        sortChange ({ column, prop, order }) {
            this.sort = order || ''
            // 如果没有 sort prop 置为空
            if (!this.sort) {
                this.type = ''
            } else {
                this.type = prop
            }
            this.getList(1)
        },
        selectChange () {
            this.type = ''
            this.sort = ''
            this.$refs.table.clearSort()
            this.getList(1)
        },
        // 页码切换
        sizeChange (val) {
            this.pageNum = 1
            this.pageSize = val
            this.getList(1)
        },
        // 页容切换
        pageChange (val) {
            this.pageNum = val
            this.getList(this.pageNum)
        },
        // 查询游戏
        filterMethod (res) {
            clearTimeout(this.timerId)
            if (!res) {
                this.gameLoading = false
                return
            }
            this.gameLoading = true
            this.timerId = setTimeout(() => {
                this.getgameList(res)
            }, 1000)
        },
        async getgameList (keyword) {
            let params = {
                keyword,
                pageIndex: 1,
                pageNum: 100
            }
            let res = await this.$http.post('/home/findGames', params)
            if (res.code === '0') {
                this.gameList = res.data
            } else {
                this.$message({
                    type: 'error',
                    message: '系统异常，请稍后再试'
                })
            }
            this.gameLoading = false
        },
        changeStatus (item) {
            this.dialogTit = `该用户的兑换码是${item.key}`
            this.currentExchangeItem = item
            this.exchangeParams = {
                id: item.id
            }
            this.dialogVisible = true
        },
        dialogSure () {
            this.$confirm(`是否兑换?`, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.$http.post('/lottrey/confirmExchange', this.exchangeParams).then(res => {
                    if (res.code === '0') {
                        this.currentExchangeItem.rewardStatus = 1
                        this.currentExchangeItem.exchangeType = this.exchangeParams.exchangeType
                        this.dialogVisible = false
                        this.$message({
                            type: 'success',
                            message: '兑换成功'
                        })
                    } else {
                        this.$message({
                            type: 'error',
                            message: '系统异常，请稍后再试'
                        })
                    }
                })
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '取消兑换'
                })
            })
        },
        toGame (id) {
            console.log(id)
            const { href } = this.$router.resolve({
                path: '/game/gameDetail',
                query: {
                    id
                }
            })
            window.open(href, '_blank')
        },
        tableFormatDate (time) {
            return formatDate(time, 'YYYY-MM-DD HH:MM:SS')
        },
        handleClose (done) {
            done()
        }
    }
}
</script>

<style lang="scss" scoped>
    .debris-user-list {
        .input-box {
            margin-top: 10px;
            font-size: 13px;
            font-weight: 500;
            .input-title {
                margin: 0 10px 0 20px;
            }
            .btn {
                margin-left: 10px;
            }
        }

        .table-box {
            margin: 20px 0;
            .cover {
                width: 80px;
                height: 80px;
                > img {
                    width: 100%;
                    height: 100%;
                }
            }
            .table-btn {
                cursor: pointer;
                color: #409EFF;
                font-size: 13px;
                font-weight: 500;
                &:hover {
                    text-decoration: underline;
                }
            }
        }

        .tools {
            padding-right: 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            p {
                font-size: 13px;
                color: #606266;
            }
        }
    }
    .dialog-slot {
        display: flex;
        align-items: center;
        justify-content: center;
        flex-direction: column;
        .dialog-item {
            margin-bottom: 20px;
        }
    }
</style>
